# import re
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import HttpResponse, redirect, render
from django.urls import reverse_lazy
from django.views.generic import TemplateView
from django.views.generic.edit import CreateView

from .forms import *
from .models import *


class SignUpView(CreateView):
    template_name = "signup.html"
    form_class = UserCreationForm
    success_url = reverse_lazy("main")

    def form_valid(self, form):
        valid = super().form_valid(form)
        login(self.request, self.object)
        return valid


def validate_username(request):
    """Check username availability"""
    username = request.GET.get("username", None)
    response = {
        "is_taken": User.objects.filter(username__iexact=username).exists()
    }
    return JsonResponse(response)


def t1(request):
    if request.method == "POST":
        print("1" * 111)
        print(request.POST)
        user_form = RegistrationForm(request.POST)
        if user_form.is_valid():
            new_user = user_form.save(commit=False)
            new_user.set_password(user_form.cleaned_data["passwd"])
            new_user.save()
            return HttpResponse("regiter successfully.")
        else:
            return HttpResponse("regiter failed.")
    else:
        user_form = RegistrationForm()
        return render(request, "t1.html", locals())


def registerView(request):
    if request.method == "POST":
        user_form = RegistrationForm(request.POST)
        if user_form.is_valid():
            new_user = user_form.save(commit=False)
            new_user.set_password(user_form.cleaned_data["passwd"])
            new_user.save()
            return HttpResponse("regiter successfully.")
        else:
            return HttpResponse("regiter failed.")
    else:
        user_form = RegistrationForm()
        captcha = CaptchaForm()
        return render(request, "register.html", locals())
